import { defineStore } from "pinia";
import Validator from '@/utils/Validator'
import emitter from '@/utils/mitt'
const useAppStore = defineStore('app', () => {
    //展开菜单
    const expandMenus = ref([])
    
    //页签
    const tabs = ref([
        {
            title:'首页',
            path:'/',
            key:'/',
            closable:false,
            name:'index'
        }
    ])
    // 活动页签
    const activeTab = ref(null)
    // 重置
    function resetApp(){
        tabs.value = [{
            title:'首页',
            path:'/',
            key:'/',
            closable:false,
            name:'index'
        }]
        expandMenus.value = []
        activeTab.value = '/'
    }
    //新增页签check
    function isTabExist(tab) {
        let flag = false
        tabs.value.forEach(ele=>{
            if(ele.key == tab.key) {
                flag = true
            }
        })
        return flag
    }
    //新增页签
    function newTab(route) {
        let name = route?.name
        let title = route?.meta?.title
        let path = route?.path
        if (Validator.isEmpty(title)) {
            title = path
        }
        let tab = {
            title,
            path,
            key:path,
            name
        }
        // 存在切换
        if(isTabExist(tab)){
            activeTab.value = tab.key
        }else{
            tabs.value.push(tab)
            activeTab.value = tab.key
        }
        //console.log(tabs.value)
    }
    //关闭页签
    function closeTab(key) {
        let idx = 0
        for(var i=0;i<tabs.value.length;i++){
            if(tabs.value[i].key == key){
                idx = i
            }
        }
        activeTab.value = tabs.value[idx - 1].key
        tabs.value.splice(idx,1)
    }

    return { resetApp,expandMenus, tabs, activeTab, newTab, closeTab, isTabExist }
},{
    persist:true
})
export default useAppStore